package com.easylinkin.linkappapi.roster.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.mechanical.entity.Mechanical;
import com.easylinkin.linkappapi.mechanical.mapper.MechanicalMapper;
import com.easylinkin.linkappapi.mechanical.service.IMechanicalService;
import com.easylinkin.linkappapi.roster.dto.LaborTeamDTO;
import com.easylinkin.linkappapi.roster.entity.LaborTeam;
import com.easylinkin.linkappapi.roster.mapper.LaborTeamMapper;
import com.easylinkin.linkappapi.roster.mapper.RailLinkappRosterPersonnelMapper;
import com.easylinkin.linkappapi.roster.service.ILaborTeamService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class LaborTeamServiceImpl extends ServiceImpl<LaborTeamMapper, LaborTeam> implements ILaborTeamService {
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    @Autowired
    private RailLinkappRosterPersonnelMapper personnelMapper;

    @Override
    public IPage<LaborTeam> selectPage(Page<LaborTeam> page, LaborTeamDTO query) {
//        QueryWrapper<LaborTeam> wrapper = new QueryWrapper<>();
//        if (StringUtils.hasText(query.getLaborTeamName())) {
//            wrapper.like("labor_team_name_", query.getLaborTeamName());
//        }
//        if (StringUtils.hasText(query.getCreditCode())) {
//            wrapper.eq("credit_code_", query.getCreditCode());
//        }
//        if (StringUtils.hasText(query.getTenantId())) {
//            wrapper.eq("tenant_id_", query.getTenantId());
//        }
//        wrapper.orderByDesc("create_time_");
//        IPage<LaborTeam> resultPage = this.page(page, wrapper);
        IPage<LaborTeam> resultPage = baseMapper.listPage(page, query);
        // 查询人数
        if (resultPage.getRecords() != null && !resultPage.getRecords().isEmpty()) {
            for (LaborTeam team : resultPage.getRecords()) {
                team.setPersonCount(personnelMapper.countByLaborTeam(team.getId()));
            }
        }
        return resultPage;
    }

    @Override
    public boolean saveLaborTeam(LaborTeamDTO dto) {
        LaborTeam entity = new LaborTeam();
        BeanUtils.copyProperties(dto, entity);
        if (dto.getContractFiles() != null) {
            try {
                entity.setContractFiles(dto.getContractFiles());
            } catch (Exception e) {

            }
        }
        Long userId = linkappUserContextProducer.getCurrent().getId();
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        Date now = new Date();
        entity.setCreatorId(userId);
        entity.setCreateTime(now);
        entity.setTenantId(tenantId);
        entity.setModifyId(userId);
        entity.setModifyTime(now);
        // 唯一性校验
        Assert.isTrue(baseMapper.selectCount(new QueryWrapper<LaborTeam>()
                .eq("tenant_id_", tenantId)
                .eq("labor_team_name_", dto.getLaborTeamName())) == 0, "劳务队伍名称已存在");
        Assert.isTrue(baseMapper.selectCount(new QueryWrapper<LaborTeam>()
                .eq("tenant_id_", tenantId)
                .eq("credit_code_", dto.getCreditCode())) == 0, "统一社会信用代码已存在");
        return this.save(entity);
    }

    @Override
    public boolean updateLaborTeam(LaborTeamDTO dto) {
        // 唯一性校验（排除自己）
        String tenantId = dto.getTenantId();
        Assert.isTrue(baseMapper.selectCount(new QueryWrapper<LaborTeam>()
                .eq("tenant_id_", tenantId)
                .eq("labor_team_name_", dto.getLaborTeamName())
                .ne("id_", dto.getId())) == 0, "劳务队伍名称已存在");
        Assert.isTrue(baseMapper.selectCount(new QueryWrapper<LaborTeam>()
                .eq("tenant_id_", tenantId)
                .eq("credit_code_", dto.getCreditCode())
                .ne("id_", dto.getId())) == 0, "统一社会信用代码已存在");
        
        // 使用UpdateWrapper强制更新所有字段，包括null值
        Long userId = linkappUserContextProducer.getCurrent().getId();
        Date now = new Date();
        
        UpdateWrapper<LaborTeam> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id_", dto.getId())
                .set("labor_team_name_", dto.getLaborTeamName())
                .set("credit_code_", dto.getCreditCode())
                .set("leader_name_", dto.getLeaderName())  // 允许null值
                .set("leader_phone_", dto.getLeaderPhone()) // 允许null值
                .set("remark_", dto.getRemark())
                .set("modify_id_", userId)
                .set("modify_time_", now);
        
        // 处理合同文件
        if (dto.getContractFiles() != null) {
            try {
                updateWrapper.set("contract_files_", new ObjectMapper().writeValueAsString(dto.getContractFiles()));
            } catch (Exception e) {
                // 处理异常
            }
        } else {
            updateWrapper.set("contract_files_", null);
        }
        
        return this.update(updateWrapper);
    }

    @Override
    public Map<String,String> deleteLaborTeam(String ids) {
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
        Map<String, String> result = new HashMap<>();
        for (Long id : idList) {
            int count = personnelMapper.countByLaborTeam(id);
            if (count > 0) {
                result.put(id.toString(), "劳务队伍下存在人员，请先解除员工与队伍关系");
                return result;
            }
        }
        this.removeByIds(idList);
        return result;
    }
} 